<?php
/**
 * 异常处理扩展类
 *
 */
class ExceptionExt extends Exception {
	private $_sErrorLogFile;
	
	/**
	 * 构造方法
	 * 所有异常都会写入错误日志
	 *
	 * @param string $message
	 * @param int $code
	 */
	public function __construct($message, $code = 0) {
		parent::__construct ( $message, $code );
		if (self::_setErrorLogFile ()) {
			self::_writeErrorLog ();
		}
	}
	
	private function _setErrorLogFile() {
		$sLogFile = Base::getConf ( 'base.errorLog' );
		if ($sLogFile) {
			$this->_sErrorLogFile = strftime ( $sLogFile );
			return true;
		} else {
			$this->_sErrorLogFile = null;
			return false;
		}
	}
	
	private function _writeErrorLog() {
		$sLog = date ( 'Y-m-d H:i:s' ) . "\t";
		$sLog .= $this->code . "\t";
		$sLog .= $this->message . "\t";
		$sLog .= var_export ( $this->getTrace (), true ) . "\n";
		@error_log ( $sLog, 3, $this->_sErrorLogFile );
	}
	
	/**
	 * 显示错误信息
	 * 如果$bTrace为true时显示错误追溯
	 *
	 * @param bool $bTrace
	 */
	public function showError($bTrace = false) {
		$sHtml = '<html>';
		$sHtml .= '<head><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /><title>错误</title><style>td, th {font-size:12px;text-align:left;}</style></head>';
		$sHtml .= '<body><h3>';
		$sHtml .= $this->message;
		$sHtml .= '</h3>';
		if ($bTrace) {
			$aTraces = $this->getTrace ();
			foreach ( $aTraces as $sRow ) {
				$sHtml .= '<table>';
				$sHtml .= '<tr><th width="50">文件</th><th>' . $sRow ['file'] . '</th></tr>';
				$sHtml .= '<tr><td>行</td><td>' . $sRow ['line'] . '</td></tr>';
				$sHtml .= '<tr><td>类</td><td>' . $sRow ['class'] . '</td></tr>';
				$sHtml .= '<tr><td>方法</td><td>' . $sRow ['function'] . '</td></tr>';
				if (count ( $sRow ['args'] )) {
					$sHtml .= '<tr><td>参数</td><td>' . var_export ( $sRow ['args'], true ) . '</td></tr>';
				}
				$sHtml .= '</table><br>';
			}
		}
		$sHtml .= '</body></html>';
		echo $sHtml;
		exit ();
	}
}